package ma.ensao.evalmetrics.controller;

import java.util.ArrayList;
import java.util.List;

import ma.ensao.evalmetrics.model.Caracteristiques;
import ma.ensao.evalmetrics.model.Metriques;
import ma.ensao.evalmetrics.model.MyFile;
import ma.ensao.evalmetrics.model.ProjetUsers;
import ma.ensao.evalmetrics.model.Propriete;
import ma.ensao.evalmetrics.model.Subcarac;
import ma.ensao.evalmetrics.model.User;
import ma.ensao.evalmetrics.util.HibernateUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

public class AffectationProjetManager {
	private Long id;
	private  MyFile myfile;
	private Caracteristiques param;
	private Subcarac sscara;
	private Propriete propriete;
	private Metriques metric;
	private List<MyFile> mfile = null;
	private List<ProjetUsers> PU;
	// R�cuperation de la liste des User � partir de la base de donn�es
	public List<User> usersList(){
		System.out.println("Affectation projet action get users");
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> usersList = new ArrayList<User>();
		try {
			usersList = (List<User>)session.createQuery("from User order by id desc").list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return usersList;
	}
	// R�cuperation de la liste des projets avec leurs users
	public List<User> usersProjetList(Long ID){
		System.out.println("Affectation projet action get users");
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> usersList = new ArrayList<User>();
		try {
			usersList = (List<User>) session.createQuery("from User as u where u.id in (SELECT PU.idUser from ProjetUsers PU where PU.idProjet="+ID+")").list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return usersList;
	}
	// R�cuperation de la liste des projet selon les status
	public List<MyFile> list(Long ID, String statut) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<MyFile> projets = null;
		try {
			System.out.println("leste projets manager"+statut);
			if (statut.equals("admin")) {
				projets = (List<MyFile>) session.createQuery("from MyFile").list();
			}else{
				projets = (List<MyFile>) session.createQuery("from MyFile as MF where MF.id in (SELECT PU.idProjet from ProjetUsers PU where PU.idUser="+ID+")").list();
			}
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return projets;
	}
	// Recupartion d'un projet donn� par son Id
	public List<MyFile> getSpecificProjet(Long Id) {
		System.out.println("UserManager get sp projet");
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<MyFile> projet = null;
		try {
			projet = (List<MyFile>) session.createQuery("from MyFile where id="+Id+"").list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return  projet;
	}
	
	public void modifier(MyFile projet, List<Long> users) {
		PU= new ArrayList<ProjetUsers>(users.size());
		org.hibernate.Session session3= HibernateUtil.getSessionFactory().getCurrentSession();;
		//trouver et supprimer les utilisateurs qui ne font plus partie du projet			
		session3.beginTransaction();
		List<ProjetUsers> usersChosenBefore= (List<ProjetUsers>) session3.createQuery("from ProjetUsers where idProjet="+projet.getId()+"").list();
		session3.getTransaction().commit();

		System.out.println("usersChosenBefore.size>>"+usersChosenBefore.size()+">>usersafter"+users.size());
		//List<Long> usersChosenUpdateMoinsUsersChosen= new ArrayList<Long>(users.size());
		if (usersChosenBefore.size() !=0){
			for(int i=0; i<usersChosenBefore.size(); i++){
				int k=0;
				for(int j=0; j<users.size(); j++){
					System.out.println("usersChosenBefore>>>"+usersChosenBefore.get(i).getIdUser()+"users>>>"+users.get(j));
					if( users.get(j).equals(usersChosenBefore.get(i).getIdUser())){
						System.out.println("===55==");
						k++;
					}
				}
				if(k==0){
					//usersChosenUpdateMoinsUsersChosen.add(users.get(i));
					Session session4 = HibernateUtil.getSessionFactory().openSession();
					session4.beginTransaction();
					System.out.println("Heeeeeeee waaaaaaaaas theeeeeeeeeeere"+ usersChosenBefore.get(i).getIdUser());
					List<ProjetUsers> usersNotChosen =(List<ProjetUsers>) session4.createQuery("from ProjetUsers where idUser ="+usersChosenBefore.get(i).getIdUser() +"AND idProjet="+projet.getId()+"").list();
					System.out.println("oooooo"+usersNotChosen.size());
					for(int g=0; i<usersNotChosen.size(); i++){
						System.out.println("piiiiiiiiiiw deleted");
						session4.delete(usersNotChosen.get(g));
						session4.getTransaction().commit();
					}
				}
			}
		}else{
			for(int i=0; i<usersChosenBefore.size(); i++){
					//usersChosenUpdateMoinsUsersChosen.add(users.get(i));
					Session session4 = HibernateUtil.getSessionFactory().openSession();
					session4.beginTransaction();
					System.out.println("Heeeeeeee waaaaaaaaas theeeeeeeeeeere"+ usersChosenBefore.get(i).getIdUser());
					List<ProjetUsers> usersNotChosen =(List<ProjetUsers>) session4.createQuery("from ProjetUsers where idUser ="+usersChosenBefore.get(i).getIdUser() +"AND idProjet="+projet.getId()+"").list();
					System.out.println("oooooo"+usersNotChosen.size());
					for(int g=0; i<usersNotChosen.size(); i++){
						System.out.println("piiiiiiiiiiw deleted");
						session4.delete(usersNotChosen.get(g));
						session4.getTransaction().commit();
					}
			}
			
		}
		
		 System.out.println("Hi I'll add in db");
			for(int i=0; i<users.size(); i++){
				Session session2 = HibernateUtil.getSessionFactory().openSession();
				session2.beginTransaction();
				List<ProjetUsers> UserDB =(List<ProjetUsers>) session2.createQuery("from ProjetUsers where idProjet="+projet.getId()+" AND idUser="+users.get(i)+"").list();
				if(UserDB.isEmpty()){
					System.out.println("for userid"+users.get(i)+"not in BD");
					ProjetUsers pu= new ProjetUsers();
					pu.setIdProjet(projet.getId());
					pu.setIdUser(users.get(i));
					//PU.add(i, pu);
					session2.save(pu);
					session2.getTransaction().commit();
				}
			}
					
	}
	public MyFile upload(MyFile myFile, List<Long> users) {
		System.out.println("tessst");
		//if(user.getFirstName().equals("") || user.getLastName().equals("") || user.getCellNo().equals("")){
			//addActionError("Donnees manquantes ");
			//return ERROR;
		//}else{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(myFile);
		
		mfile = (List<MyFile>) session.createQuery("from MyFile where id=(select max(id) from MyFile)").list();
		ParamPardefaut();	
		session.save(param);
		session.save(sscara);
		session.save(propriete);		
		session.save(metric);
		session.getTransaction().commit();
		
		 PU= new ArrayList<ProjetUsers>();
			for(int i=0; i<users.size(); i++){
				Session session2 = HibernateUtil.getSessionFactory().openSession();
				session2.beginTransaction();
				ProjetUsers pu= new ProjetUsers();
				pu.setIdProjet(myFile.getId());
				pu.setIdUser(users.get(i));
				PU.add(i, pu);
				System.out.println("3");
				session2.save(PU.get(i));
				System.out.println("4");
				session2.getTransaction().commit();
				System.out.println("5");
			}
		return myFile;
	}
	public void ParamPardefaut(){
		param= new Caracteristiques();
		sscara= new Subcarac();
		propriete=new Propriete();
		metric= new Metriques();
		
		param.setFonctionnalite(new Long(1));
		param.setReliabilite(new Long(1));
		param.setUsabilite(new Long(1));
		param.setMaintenabilite(new Long(1));
		param.setEfficacite(new Long(1));
		param.setPortabilite(new Long(1));
		param.setId(new Long(1));
		
		sscara.setConvenance(new Long(1));
		sscara.setExactitude(new Long(1));
		sscara.setSecurite(new Long(1));
		sscara.setCompliance(new Long(1));
		sscara.setInteroperabilite(new Long(1));
		sscara.setConvenance(new Long(1));
		sscara.setMaturite(new Long(1));
		sscara.setFausseTolerance(new Long(1));
		sscara.setRecoverabilite(new Long(1));
		sscara.setClarete(new Long(1));
		sscara.setLearnabilite(new Long(1));
		sscara.setAttractivite(new Long(1));
		sscara.setComportement_time(new Long(1));
		sscara.setUtilisation_Ressource(new Long(1));
		sscara.setVariabilite(new Long(1));
		sscara.setAnalyse(new Long(1));
		sscara.setStabilite(new Long(1));
		sscara.setTestabilite(new Long(1));
		sscara.setAdabtabilite(new Long(1));
		sscara.setInstabilite(new Long(1));
		sscara.setConformite(new Long(1));
		sscara.setRemplacabilite(new Long(1));
		sscara.setId(id);
			
		
		propriete.setId(id);
		propriete.setAbstraction(new Long(1));
		propriete.setCohesion(new Long(1));
		propriete.setComplexite(new Long(1));
		propriete.setComposition(new Long(1));
		propriete.setConsistence(new Long(1));
		propriete.setCoupling(new Long(1));
		propriete.setDependence(new Long(1));
		propriete.setEncapsulation(new Long(1));
		propriete.setHeritage(new Long(1));
		propriete.setInstabilite(new Long(1));
		propriete.setMessage(new Long(1));
		propriete.setModularite(new Long(1));
		propriete.setNbmethodes(new Long(1));
		propriete.setPrecision(new Long(1));
		propriete.setSize(new Long(1));
		propriete.setSizemethodes(new Long(1));
		propriete.setSpecialisation(new Long(1));
		propriete.setStabilite(new Long(1));
		propriete.setTolerence(new Long(1));
		
		propriete.setId(id);
		propriete.setAbstraction(new Long(1));
		propriete.setCohesion(new Long(1));
		propriete.setComplexite(new Long(1));
		propriete.setComposition(new Long(1));
		propriete.setConsistence(new Long(1));
		propriete.setCoupling(new Long(1));
		propriete.setDependence(new Long(1));
		propriete.setEncapsulation(new Long(1));
		propriete.setHeritage(new Long(1));
		propriete.setInstabilite(new Long(1));
		propriete.setMessage(new Long(1));
		propriete.setModularite(new Long(1));
		propriete.setNbmethodes(new Long(1));
		propriete.setPrecision(new Long(1));
		propriete.setSize(new Long(1));
		propriete.setSizemethodes(new Long(1));
		propriete.setSpecialisation(new Long(1));
		propriete.setStabilite(new Long(1));
		propriete.setTolerence(new Long(1));
		
			metric.setMPF(new Long(1));
			metric.setWMC(new Long(1));
			metric.setCyclo(new Long(1));
			metric.setVG(new Long(1));
			metric.setNOC(new Long(1));
			metric.setLOC(new Long(1));
			metric.setDIT(new Long(1));
			metric.setCLOC(new Long(1));
			metric.setNOM(new Long(1));
			metric.setPOF(new Long(1));
			metric.setMHF(new Long(1));
			metric.setAHF(new Long(1));
			metric.setRFC(new Long(1));
			metric.setAPF(new Long(1));
			metric.setMPC(new Long(1));
			metric.setTCC(new Long(1));
			metric.setAbs(new Long(1));
			metric.setD(new Long(1));
			metric.setI(new Long(1));
			metric.setNOI(new Long(1));
			metric.setCa(new Long(1));
			metric.setCe(new Long(1));
			metric.setClasses(new Long(1));
			
			System.out.println("idddddddddddd"+mfile.get(0).getId());
				metric.setId(mfile.get(0).getId());
				param.setId(mfile.get(0).getId());
				sscara.setId(mfile.get(0).getId());
				propriete.setId(mfile.get(0).getId());
				System.out.println("------------"+metric.getId()+"My main==="+param.getMaintenabilite()+"My Fonct"+param.getFonctionnalite());
		
	}
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public MyFile getMyfile() {
		return myfile;
	}
	public void setMyfile(MyFile myfile) {
		this.myfile = myfile;
	}
	public Caracteristiques getParam() {
		return param;
	}
	public void setParam(Caracteristiques param) {
		this.param = param;
	}
	public Subcarac getSscara() {
		return sscara;
	}
	public void setSscara(Subcarac sscara) {
		this.sscara = sscara;
	}
	public Metriques getMetric() {
		return metric;
	}
	public void setMetric(Metriques metric) {
		this.metric = metric;
	}
	public List<MyFile> getMfile() {
		return mfile;
	}
	public void setMfile(List<MyFile> mfile) {
		this.mfile = mfile;
	}
	public List<ProjetUsers> getPU() {
		return PU;
	}
	public void setPU(List<ProjetUsers> pU) {
		PU = pU;
	}
	/**
	 * @return the propriete
	 */
	public Propriete getPropriete() {
		return propriete;
	}
	/**
	 * @param propriete the propriete to set
	 */
	public void setPropriete(Propriete propriete) {
		this.propriete = propriete;
	}
}
